<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Member extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->helper(array('form','debug','directory','file'));
		$this->load->model("member/member_model");
		$this->load->library('form_validation');
	}

	public function home()
	{
		$this->_loadScreen('home');
	}

	public function ask_question()
	{
		$this->_loadScreen('ask_question');
	}

	public function do_ask_question()
	{
		if($this->do_question_validation())
		{
			$param = array();
				
			if($this->input->post('txtTitle'))
			{
				$param['title'] = $this->input->post('txtTitle');
			}
				
			if($this->input->post('txtQuestion'))
			{
				$param['question'] = $this->input->post('txtQuestion');
			}
				
			$param['priority_id'] = $this->input->post('selPriority');
			$param['ask_date'] = date("Y-m-d");
			$param['language_id'] = '3';
				
			$result = array();
			$result = $this->member_model->ask_question($param);
			if( isset($result['insert_id']) && $result['insert_id'] > 0 )
			{
				debug_printr($this->uploadFile());
			}
			else
			{
				$data = array();
				$data['question_failiure'] = 'Unable to submit question';
				$this->_loadScreen('ask_question',$data);
			}
		}


	}

	private function _loadScreen($screen = 'home', $params = null, $cache = 0)
	{
		$this->load->view("member/header");
		$this->load->view("member/topnav");
		$this->load->view("member/$screen",$params);
		$this->load->view("member/footer");

		if($cache > 0)
		{
			$this->output->cache($cache);
		}
	}

	private function _create_upload_directory()
	{
		$directory = './uploads/' . Date('Y-m') . '/' . Date('d');
		if(!is_dir($directory))
		{
			mkdir($directory,0777,true);
		}
	}

	private function uploadFile()
	{
		$this->_create_upload_directory();

		$directory = Date('Y-m') ."/". Date('d');
		$config['upload_path'] = './uploads/'.$directory;
		$config['allowed_types'] = 'gif|jpg|jpeg|png';
		$config['max_size']	= '1024';

		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload())
		{
			return $this->upload->display_errors();
		}
		else
		{
			return $this->upload->data();
		}
	}

	private function do_question_validation()
	{
		$this->form_validation->set_rules('txtTitle', 'Title', 'required');
		$this->form_validation->set_rules('txtQuestion','Question','required|max_length[200]');
		$this->form_validation->set_rules('selPriority','Priority','required');

		if ($this->form_validation->run() == FALSE)
		{
			$this->_loadScreen('ask_question');
		}
		else
		{
			return true;
		}
	}

}